<template>
    <el-card shadow="always" >
        <!-- <div class="flex items-center  mb-4">
        <span>关键词</span>    
        <el-input placeholder="Please Input" style="width: 380px;" class="ml-4"></el-input>
            <el-button type="primary" size="default" @click="">搜索</el-button>
            <el-button class="" plain size="default" @click="">重置</el-button>  
        </div> -->
       <el-form  :mode="searchForm"  label-width="80px" class="mb-3" >
       <el-row :gutter="8">
        <el-col :span="8" >
            <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="管理员昵称" clearable></el-input>
            </el-form-item>
        </el-col>

        <el-col :span="8" :offset="8">
            <el-form-item>
            <div class="">
                <el-button type="primary" @click="searchData">搜索</el-button>
                <el-button plain @click="resetSearchForm">重置</el-button>
            </div>
            </el-form-item>
        </el-col>
       </el-row>

       </el-form>
       

      <div class="flex item-center justify-between mb-4">
        <el-button type="primary" size="small" @click="addReport">新增</el-button> 
        
        <el-tooltip
          offect="dark"
          content="刷新"
          placement="top"
        >
          <el-button text @click="frush">
            <el-icon :size="20"><Refresh /></el-icon>
          </el-button> 
        </el-tooltip>
      </div>
      <el-table :data="pageData" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="管理员" width="200" >
            <template #default="{ row }">
                <div class="flex items-center ">
                    <el-avatar :size="40" :src="row.avater" >
                        <img
                            src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                        />
                    </el-avatar>
                    <div class="mt-0 ml-3">
                      <h5>{{ row.username }}</h5>
                      <small>ID:{{ row.id }}</small>
                    </div>
                </div>      
            </template>
        </el-table-column>

        <el-table-column  label="所属管理员" align="center" >
            <template #default="{ row }">
                {{ row.role ?  row.role : '-'}}
            </template>
        </el-table-column>

        <el-table-column  label="状态" width="120" >
            <template #default="{ row }">
                <el-switch :modelValue="row.status" :active-value="1" :inactive-value="0"
                @change="handleStatusChange($event,row)"
                :loading="row.statusLoading"
                :disabled="row.username=='张五'"
                >
                </el-switch>
                
            </template>
        </el-table-column>

        <el-table-column label="操作" align="center" >
          <template #default="scope">
            <small v-if="scope.row.username=='张五'" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
              <el-button text type="primary" size="small"  @click="updateReport(scope.row)">修改</el-button>  
              <el-popconfirm title="确认删除？" confirm-button-text="确认" cancel-button-text="取消" @confirm="deleteReport(scope.row.id)">
                <template #reference>
                  <el-button text type="primary" size="small" >删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        
      </el-table>
      <div class="flex items-center justify-center mt-5">
            <el-pagination 
            background 
            v-model:current-page="currentPage1"
            v-model:page-size="pageSize1"
            :page-sizes="[2, 3, 4, 5]"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
        </div>
  
      
  <FormDrawer :title="drawerTitle" ref="formDrawerRef" @submit="handleSubmit">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" ></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="avater">
      
              <ChooseImage v-model="form.avater" />
            </el-form-item>
            <el-form-item label="所属角色" prop="role_id">
              <el-select v-model="form.role_id" value-key="" placeholder="请选择所属角色" clearable filterable @change="">
                <el-option v-for="item in tableData"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id">
                </el-option>
              </el-select>
              
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0">
              </el-switch>    
            </el-form-item>
        </el-form>
  </FormDrawer>   
</el-card>
</template>
<script setup>
import { ref,reactive,computed } from 'vue'
import FormDrawer from "@/components/FormDrawer.vue"
import ChooseImage from "@/components/ChooseImage.vue";

const tableData = ref([]) // 总条数,即所有数据
function getData(){
  tableData.value = [
    {id:1001,status:1,avater:"https://img2.baidu.com/it/u=1028011339,1319212411&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313",username:"张五",title:"title01",content:"content01","addTime":"2024-01-03"},
    {id:201,status:0,avater:"",username:"张三",title:"title02",content:"content02","addTime":"2024-01-03"},
    {id:3001,status:1,avater:"",username:"张三",title:"title03",content:"content03","addTime":"2024-01-03"},
    {id:4001,status:1,avater:"",username:"张三02",title:"title04",content:"content04","addTime":"2024-01-03"},
    {id:501,status:1,avater:"",username:"张三03",title:"title05",content:"content05","addTime":"2024-01-03"},
   

  ]
  tableData.value.map(o=>{
    o.statusLoading = false
  })
  total1.value=tableData.value.length
  console.log(`xx:${tableData.value[0]}`)
}


/////// 前端分页 //////

const currentPage1 = ref(1) // 当前页码
const pageSize1 = ref(2)  // 选择每页几条
const total1 = ref(0)
const background = ref(false)
const disabled = ref(false)
const pageData = ref([])

// 分页逻辑
function getPageDatas() {
  pageData.value = []
  console.log(pageSize1.value)
  for (let i =  (currentPage1.value - 1) * pageSize1.value; i < tableData.value.length; i++) {
    // console.log(tableData.value[i])
    pageData.value.push(tableData.value[i])
    if (pageData.value.length === pageSize1.value) break;
  }
  console.log(pageData.value)
}


const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize1.value = val;
  currentPage1.value = 1; // 选择每页几条时，自动打到第一页重新计算数据
  getPageDatas() 
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage1.value = val;
  getPageDatas()
}

getData() // 加载全部数据
getPageDatas() // 根据分页逻辑，添加分页的数据，页面上正在展示的数据



// 搜索
const searchTitle = ref("")
searchTitle.value="dd"
const searchForm = reactive(
    {
         keyword:""
    }
)
const searchData2 = ref([])
const searchData = ()=>{
    searchData2.value = []
    for(const i in tableData.value){
        console.log(tableData.value[i]["username"])
        if(searchForm.keyword == tableData.value[i]["username"]) {
          console.log("?")
          searchData2.value.push(tableData.value[i])
          
        }
    }
    console.log(`搜索数据1：${searchData2.value.length}`)
    if(searchData2.value){
      
      tableData.value = []
      for(const i in searchData2.value){
        tableData.value.push(searchData2.value[i])
        console.log(`搜索数据2：${ tableData.value[i]["username"]}`)
      }

      
      total1.value = searchData2.value.length
      getPageDatas()
      
      console.log(`搜索数据3：${pageData.value.length}`)
    }
}



const resetSearchForm=()=>{
  searchForm.keyword = ""
  searchData2.value = []
  getData()
  getPageDatas()
}


// 修改状态
const handleStatusChange=(status,row)=>{
  row.statusLoading = true
  console.log(`ststus:${status}`)
  row.status=status
  row.statusLoading = false
}

const frush = ()=>{
  currentPage1.value = 1;
  getPageDatas()
}
////////////
// 删除
function deleteReport(res){
  loading.value = true
  console.log("删除。。。")
  console.log(res)
}




// 分页
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(3)
// 重置表单,深拷贝
function resetForm(row=false){
  if(formRef.value) formRef.value.clearValidate()
  // if(row){
  //   // 修改赋值
  //   for(const key in form){
  //     form[key] = row[key]
  //   }
  // }else{
  //   // 增加置为空
  //   for(const key in form){
  //     form[key] = ""
  //   }
  // }
}
// 新增
const editId = ref(0) // 区别新增与修改
const drawerTitle = computed(()=>editId.value ? "编辑" : "新增" )
const form = reactive({
    username:"",
    password:"",
    role_id:null,
    status:1,
    avater:""

})
const formDrawerRef = ref(null) // 控制打开关闭
const formRef = ref(null) // 规则
const rules = {
  username:[{
        required: true,
        message: '标题不能为空',
        trigger: 'blur'
    }]
}

const addReport = ()=>{
  editId.value = 0
  resetForm()
  formDrawerRef.value.open()
  // 要么采用重新赋值为空，要么resetForm()
 
  form.username="",
  form.password="",
  form.role_id=null,
  form.status=1,
  form.avater=""
 
  
  
}
// 修改
const updateReport = (row) => {
  console.log("修改report...")
  console.log(row)
  editId.value = row.id
  resetForm(row)
  formDrawerRef.value.open()
  form.title = row.title
  form.content = row.content
 
  
}
const handleSubmit = ()=>{
    formRef.value.validate((valid)=>{
        if(!valid) return
        
        formDrawerRef.value.showLoading()
        // const fun = editId.value ? updateImageClass({"editId":editId.value,"form":form}) : createImageClass(form)
        // fun.then(res=>{
        //     // toast("新增成功")
        //     getData(editId.value ? currentPage.value : 1)
        //     formDrawerRef.value.close()
        // })
        .finally(()=>{
            formDrawerRef.value.hideLoading()
        })
  
    })
}
</script>